import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2024-10-07
 * Time: 19:22
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap() {
        this.elem =new int[10];
    }
    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }

    /**
     * 创建堆
     * O(N)-O(logN+1)-->O(N)
     */
    public void createHeap() {
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            shiftDown(parent,this.usedSize);
        }
    }
    /**
     * 向下调整--大根堆
     * O(longN+1)
     * @param parent 每棵子树向下调整的 起始位置
     * @param usedSize 判断 每棵子树什么时候 调整结束
     */
    private void shiftDown(int parent,int usedSize) {
        int child = parent * 2 + 1;
        while (child < usedSize) {
            if(child + 1 < usedSize && elem[child] < elem[child+1]) {
                child++;
            }
            if(elem[child] > elem[parent]) {
                swap(elem,parent,child);
                parent = child;
                child = parent * 2 + 1;
            }else {
                break;
            }
        }
    }
    private void swap(int[] elem,int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    //插入元素
    public void offer(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }
    private boolean isFull() {
        return usedSize == elem.length;
    }
    /**
     * 向上调整
     * O(NlogN)
     * @param child
     */
    public void shiftUp(int child) {
        int parent = (child-1)/2;
        while(parent >= 0) {
            if(elem[child] > elem[parent]) {
                swap(elem,child,parent);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    //删除堆顶元素
    public int poll() {
        if(isEmpty()) {
            throw new NullArrayException("数组为空");
        }
        int val = elem[0];
        swap(elem,0,usedSize-1);
        shiftDown(0,--usedSize);
        return val;
    }

    private boolean isEmpty() {
        return usedSize == 0;
    }

    public int peek() {
        if(isEmpty()) {
            throw new NullArrayException("数组为空");
        }
        return elem[0];
    }

    /**
     * 1. 建堆
     *    升序：建大堆
     *    降序：建小堆
     * 2. 利用堆删除思想来进行排序
     *    建堆和堆删除中都用到了向下调整，因此掌握了向下调整，就可以完成堆排序
     */
    public void heapSort() {
        int end = usedSize-1;
        while(end >= 0){
            swap(elem,0,end);
            shiftDown(0,usedSize);
            end--;
        }
    }
}
